const db = require('../database/db');
const jwt = require('jsonwebtoken');
const fetch = require('node-fetch');
class GlobalUtil {
    //数据库查询async
    asyncQuery(sql, data) {
        return new Promise((resolve, reject) => {
            db.query(sql, data, (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(result);
                }
            })
        })
    }
    //token验证async
    asyncVerify(token) {
        return new Promise((resolve, reject) => {
            jwt.verify(token, process.env.SECRETKEY, (err, decoded) => {
                if (err) {
                    reject(err);
                } else {
                    resolve(decoded);
                }
            })
        })
    }

    //获取客户端ip
    asyncGetClientIP(req) {
        return new Promise((resolve, reject) => {
            try {
                const ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
                resolve(ip);
            } catch (error) {
                reject(error);
            }
        })
    }
    
    //随机生成六位数字验证码
    generateRandomCode() {
        let code = '';
        for (let i = 0; i < 6; i++) {
            code += Math.floor(Math.random() * 10);
        }
        return code;
    }
    //获取符合MySQL中DateTime格式的东八区时间
    //addTime:当前时间+addTime，单位秒(可带符号)
    getDateTime(addTime = 0) {
        return new Date(new Date().getTime() + (8 * 60 * 60 * 1000) + (addTime * 1000)).toISOString().slice(0, 19).replace('T', ' ');
    }

    //转换时间
    formatRelativeTime(logTime) {
        // 检查 logTime 是否为 null 或 undefined
        if (logTime === null || logTime === undefined) {
            return '未知时间';
        }
    
        // 直接使用 Date 对象解析 ISO 8601 格式的字符串
        const loginTime = new Date(logTime);
        const currentTime = new Date();
    
        // 计算时间差（毫秒）
        const diff = currentTime - loginTime;
    
        // 定义不同时间单位对应的毫秒数
        const minute = 60 * 1000;
        const hour = 60 * minute;
        const day = 24 * hour;
    
        if (diff < minute) {
            return '刚刚';
        } else if (diff < hour) {
            const minutes = Math.floor(diff / minute);
            return `${minutes}分钟前`;
        } else if (diff < day) {
            const hours = Math.floor(diff / hour);
            return `${hours}小时前`;
        } else {
            const days = Math.floor(diff / day);
            return `${days}天前`;
        }
    }
}
module.exports = new GlobalUtil();